
<template>
  <view class="uni-container">
    <uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
      <uni-forms-item name="hotelName" label="名称" required>
  <uni-easyinput placeholder="民宿名称" v-model="formData.hotelName" trim="both" />
</uni-forms-item>
<uni-forms-item name="hotel_image" label="图片地址">
  <uni-easyinput placeholder="民宿缩略图，用于在列表或搜索结果中预览显示" v-model="formData.hotel_image" trim="both" />
</uni-forms-item>
<uni-forms-item name="hotel_address" label="详细地址" required>
  <uni-easyinput placeholder="民宿详细地址" v-model="formData.hotel_address" trim="both" />
</uni-forms-item>
<uni-forms-item name="serviceList" label="服务">
  <uni-data-checkbox :multiple="true" v-model="formData.serviceList" collection="service" field="name as text, _id as value" @change="serviceChange"/>
</uni-forms-item>
<uni-forms-item name="phone" label="电话" required>
  <uni-easyinput placeholder="民宿电话" v-model="formData.phone" />
</uni-forms-item>
<uni-forms-item name="number" label="人数">
  <uni-easyinput placeholder="可居住人数" type="number" v-model="formData.number" />
</uni-forms-item>
<uni-forms-item name="price" label="价格">
  <uni-easyinput placeholder="价格/晚" type="number" v-model="formData.price" />
</uni-forms-item>
<uni-forms-item name="district" label="附近商圈">
  <uni-easyinput placeholder="民宿附近商圈" v-model="formData.district" />
</uni-forms-item>
<uni-forms-item name="city" label="所在城市">
  <uni-easyinput placeholder="民宿所在城市" v-model="formData.city" />
</uni-forms-item>
<uni-forms-item name="is_on_open" label="是否营业" v-if="$hasRole('admin')">
  <switch @change="openChange" :checked="formData.is_on_open" />
</uni-forms-item>
<uni-forms-item name="hotel_desc" label="详细描述">
	<view class="view">
		<view class="grace-rich-text">
			<jinEdit v-if="formData.hotel_desc" :html="formData.hotel_desc" placeholder="详细描述" @change="changeDesc" uploadFileUrl="/#"></jinEdit> 
		</view>
	</view>
</uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" @click="submit">提交</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/hotel.js';
	
	import jinEdit from '@/components/jin-edit/jin-edit.vue';

  const db = uniCloud.database();
	const dbCmd = db.command
	const $ = dbCmd.aggregate
  const dbCollectionName = 'xinxuan_hotel';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
        formData: {
					"hotelName": "",
					"hotel_desc": null,
					"hotel_image": "",
					"hotel_address": "",
					"serviceList": [],
					"phone": "",
					"number": null,
					"price": null,
					"district": "",
					"city": "",
					"is_on_open": null
				},
				serviceNameList:[],
        formOptions: {},
        rules: {
          ...getValidator(["hotelName","hotel_desc","hotel_image","hotel_address","serviceList","phone","number","price","district","city","is_on_open"])
        }
      }
    },
		components: { jinEdit },
    onLoad(e) {
      const id = e.id
      this.formDataId = id
      this.getDetail(id)
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.submit().then((res) => {
          this.submitForm(res)
        }).catch((errors) => {
          uni.hideLoading()
        })
      },
			
			/**
			 * 修改营业状态
			 * @param {Object} e
			 */
			openChange(e){
				this.formData.is_on_open = e.detail.value
			},
			
			/**
			 * 修改服务
			 * @param {Object} e
			 */
			serviceChange(e){
				//先置空 再赋值
				this.serviceNameList = []
				e.detail.data.map((item)=>{this.serviceNameList.push(item.text)})
			},
			

      submitForm(value) {
				if(this.serviceNameList.length != 0){
					value.serviceNameList = this.serviceNameList
				}
				console.log()
        // 使用 clientDB 提交数据
        db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            icon: 'none',
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
			
			changeDesc(e){
				this.formData.hotel_desc = e.html
				console.log(this.formData.hotel_desc)
			},
			
      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
				this.$request('hotel/getDetail', id)
				    .then( ({data}) => {
							if (data) {
							    this.formData = data[0]
							  }
				    }).catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(err => {
						uni.hideLoading()
					})
        // db.collection(dbCollectionName).doc(id).field('hotelName,hotel_desc,hotel_image,hotel_address,serviceList,phone,number,price,district,city,comment_count,is_on_open,create_date,seller_note').get().then((res) => {
        //   const data = res.result.data[0]
        //   if (data) {
        //     this.formData = data
        //   }
        // }).catch((err) => {
        //   uni.showModal({
        //     content: err.message || '请求服务失败',
        //     showCancel: false
        //   })
        // }).finally(() => {
        //   uni.hideLoading()
        // })
      }
    }
  }
</script>

<style>
	.view{font-size:28upx;}
	.grace-rich-text{background-color: #efefef;}
  .uni-container {
    padding: 15px;
  }

  .uni-input-border,
  .uni-textarea-border {
    width: 100%;
    font-size: 14px;
    color: #666;
    border: 1px #e5e5e5 solid;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .uni-input-border {
    padding: 0 10px;
    height: 35px;

  }

  .uni-textarea-border {
    padding: 10px;
    height: 80px;
  }

  .uni-button-group {
    margin-top: 50px;
    display: flex;
    justify-content: center;
  }

  .uni-button {
    width: 184px;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
    line-height: 1;
    margin: 0;
  }
</style>
